<?php
namespace app\common\model\order;

use app\common\enum\user\balanceLog\BalanceLogSceneEnum as SceneEnum;
use app\common\model\BaseModel;
use app\common\model\car\Car;
use app\common\model\user\AttestationInfo;
use app\common\model\user\BalanceLog;
use app\common\model\user\User;
use think\facade\Db;

/**
 * 订单模型模型
 */
class CarOrder extends BaseModel
{
    protected $pk = 'id';
    protected $name = 'car_order';

    public function user()
    {
        return $this->belongsTo(User::Class)->field('user_id,nickName,avatarUrl');
    }
    public function takeruser()
    {
        return $this->belongsTo(User::Class,'take_user_id','user_id')->field('user_id,nickName,avatarUrl');
    }

    public function carplan()
    {
        return $this->belongsTo(CarOrderPlan::Class,'order_id');
    }

    public function attestation()
    {
        return $this->belongsTo(AttestationInfo::Class,'user_id','user_id');
    }

    /*
     * 发布
     * */
    public function add($data,$user)
    {
        $times = $this->date_time(1);
        $w[] = ['create_time','between',$times];
        $count = $this->where($w)->count();
        $data['user_id'] = $user['user_id'];
        $data['app_id'] = self::$app_id;
        $data['ordernum'] = 'N_'.date("Ymd").($count+1);
        unset($data['token']);
        $scheduling = "";
        if(isset($data['scheduling'])){
            $scheduling = $data['scheduling'];
            $scheduling_1 = json_decode($scheduling,1);
            $times = $scheduling_1[0]['date_time'];
            unset($data['scheduling']);
        }

        unset($data['scheduling']);
        $data['create_time'] = time();
        $data['star_time'] = strtotime($data['star_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $res = $this->insertGetId($data);
        if($res){
            $datas = array(
                'user_id'=>$user['user_id'],
                'create_time'=>time(),
                'content'=>'您的订单：'.$data['ordernum'].'已经下单成功！'
            );
            $id = Db::name('order_messages')->insertGetId($datas);
            if($scheduling){
                $sldata_2 = array(
                    'order_id'=>$res,
                    'content'=>$scheduling,
                    'create_time'=>time(),
                    'date_time' =>strtotime($times)
                );
                Db::name("car_order_trip")->insertGetId($sldata_2);
            }


        }
        return $res;
    }

    /*
     * 修改
     * */
    public function edit($data)
    {
        unset($data['token']);
        unset($data['create_time']);
        unset($data['carplan']);
        unset($data['user']);
        unset($data['takeruser']);
        unset($data['attestation']);
        unset($data['order_trip']);
        $data['update_time'] = time();
        if(isset($data['star_time'])){
            $data['star_time'] = strtotime($data['star_time']);
        }
        if(isset($data['end_time'])){
            $data['end_time'] = strtotime($data['end_time']);
        }
        $scheduling = "";
        if(isset($data['scheduling'])){
            $scheduling = $data['scheduling'];
            $scheduling_1 = json_decode($scheduling,1);
            $times = $scheduling_1[0]['date_time'];
            unset($data['scheduling']);
        }

        $res = $this->where(array('id'=>$data['id']))->update($data);
        if($res){
            if($scheduling){
                $sldata_2 = array(
                    'order_id'=>$data['id'],
                    'content'=>$scheduling,
                    'date_time' =>strtotime($times)
                );
                Db::name("car_order_trip")->where(array('order_id'=>$data['id']))->update($sldata_2);
            }
        }

        return $res;
    }


    /*
     * 接单
     * */
    public function receivingOrders($data,$user)
    {
        //判断订单状态
        $res = $this->check_order($data['id']);
        if(!$res) {return false;}
        $data['take_user_id'] = $user['user_id'];
        $data['owner_status'] = 0;
        //dump($data);die;
        unset($data['token']);
        $res = $this->update($data);

        return $res;
    }

    /*
     * 支付押金
     * $type 1用户，2车主
     * */
    public function pay($id,$user,$type,$password)
    {
        //扣除余额
        $info = $this->find($id);

        if($info['owner_status'] >0 || $info['status'] >1){
            $this->error = '订单状态错误，无法支付';
            return false;
        }
        if($user['balance']<$info['front_money']){
            $this->error = '余额不足';
            return false;
        }
        $balance = $user['balance'] - $info['front_money'];

        $user_model = new User();
        if($info['front_money']>0){
            $pwd = md5(md5($password . '###' . $user['salt']));
            if($user['password'] !=$pwd){
                $this->error = '密码错误';
                return false;
            }
        }
        $BalanceLogModel = new BalanceLog();
        $user_model->where(array('user_id'=>$user['user_id']))->update(array('balance'=>$balance));
        $BalanceLogModel::add(SceneEnum::CONSUME, [
            'user_id' => $user['user_id'],
            'money' => $info['front_money'],
            'remark' => '支付接单定金',
        ], [$info['front_money']]);
        if($type==1){
            $data['id'] = $id;
            $data['status'] = 1;
            $data['pay_time'] = time();
        }else{
            $data['take_user_id'] = $user['user_id'];
            $data['id'] = $id;
            $data['owner_status'] = 1;
            $data['owner_pay_time'] = time();
            $datas = array(
                'user_id'=>$info['user_id'],
                'create_time'=>time(),
                'type'=>2,
                'content'=>'您的订单：'.$info['ordernum'].'已经有车主接单！'
            );
            Db::name('order_messages')->insertGetId($datas);
        }

        $res = $this->update($data);
        return $res;
    }

    //分配车辆
    public function distribution_car($id,$car)
    {
        $detail = $this->find($id);
        if($detail['owner_status'] !=1){
            $this->error = '订单状态错误！';
            return false;
        }

        if($detail['end_time']<time()){
            $this->error = '已经过了订单结束时间！';
            return false;
        }
        $car_arr = json_decode($car,1);
        $model = new CarOrderPlan();
        $res = $model->plan($id,$car_arr);
        if(!$res){
            $this->error = $model->getError();
        }
        return $res;

    }

    public function details($id)
    {
        $res = $this->with(['user','takeruser','attestation'])->find($id);
        $res['lineInformation'] = json_decode($res['lineInformation'],1);
        $res['star_address'] = json_decode($res['star_address'],1);
        $res['end_address'] = json_decode($res['end_address'],1);
        $res['driver_price'] = json_decode($res['driver_price'],1);
        //$res['waypoistr'] = json_decode($res['waypoistr'],1);
        if($res['star_time']>time()){
            $res['travel_status'] = 0;
            //$res['travel_status_name'] = '未出行';
        }
        if($res['star_time']<time() && $res['end_time']>time()){
            $res['travel_status'] = 1;
            //$res['travel_status_name'] = '进行中';
        }
        if($res['end_time']<time()){
            $res['travel_status'] = 2;
            //$res['travel_status_name'] = '已完成';
        }
        $res['star_time'] = date('Y-m-d H:i',$res['star_time']);
        $res['end_time'] = date('Y-m-d H:i',$res['end_time']);
        $car_model = new CarOrderPlan();
        $res['carplan'] = $car_model->alias('co')
                ->field('co.id,co.driver_name,co.driver_phone,c.car_number,c.car_info4,ct.type_name')
                ->join('jjjshop_car c','co.car_id=c.car_id','left')
                ->join('jjjshop_car_type ct','c.car_type=ct.type_id')
                ->where(array('co.order_id'=>$id))->select()->toArray();
        $order_trip = Db::name("car_order_trip")->field('content')->where(array('order_id'=>$res['id']))->find();


        //$order_trip['content'] = json_decode($order_trip['content'],1);

        $res['order_trip'] = json_decode($order_trip['content'],1);
        return $res;
    }

    //后台订单详情
    public function admin_details($id)
    {
        $res = $this->with(['user','takeruser'])->find($id);
        $res['lineInformation'] = json_decode($res['lineInformation'],1);
        $star_address = json_decode($res['star_address'],1);
        $end_address = json_decode($res['end_address'],1);
        $res['driver_price'] = json_decode($res['driver_price'],1);

        $res['waypoistr'] = json_decode($res['waypoistr'],1);
        $res['star_address'] = $star_address['b_name'];
        $res['end_address'] = $end_address['d_name'];
        $car_model = new CarOrderPlan();
        $car = $car_model->alias('co')
            ->field('co.driver_name,co.driver_phone,c.car_number')
            ->join('jjjshop_car c','co.car_id=c.car_id','left')
            ->where(array('co.order_id'=>$res['id']))->select()->toArray();
        $scheduling = Db::name("car_order_trip")->where(array("order_id"=>$res['id']))->find();
        $content = json_decode($scheduling['content'],1);
        if($scheduling){
            $date_time = array_column($content,'date_time');
            array_multisort($date_time,SORT_ASC,$content);
        }
        $scheduling['content'] = $content;
        $res['scheduling'] = $scheduling;

        if($res['status']==0){
            $res['status_name'] = '用户未支付';
        }elseif ($res['status']==1){
            $res['status_name'] = '用户已支付';
        }elseif ($res['status']==3){
            $res['status_name'] = '退单申请中';
        }elseif ($res['status']==4){
            $res['status_name'] = '退单已驳回';
        }else{
            $res['status_name'] = '用户已取消';
        }
        if($res['owner_status']==0){
            $res['owner_status_name'] = '车主已接单';
        }elseif ($res['owner_status']==1){
            $res['owner_status_name'] = '车主已支付押金';
        }elseif ($res['owner_status']==2){
            $res['owner_status_name'] = '已退单';
        }elseif ($res['owner_status']==3){
            $res['owner_status_name'] = '退单申请中';
        }elseif ($res['owner_status']==4){
            $res['owner_status_name'] = '退单已驳回';
        }else{
            $res['owner_status_name'] = '未有车主接单';
        }

        if($res['star_time']>time()){
            $res['active'] = 0;
            $res['travel_status_name'] = '未出行';
        }
        if($res['star_time']<time() && $res['end_time']>time()){
            $res['active'] = 1;
            $res['travel_status_name'] = '进行中';
        }
        if($res['end_time']<time()){
            $res['active'] = 2;
            $res['travel_status_name'] = '已结束行程';
        }
        $res['star_time'] = date('Y-m-d H:i',$res['star_time']);
        $res['end_time'] = date('Y-m-d H:i',$res['end_time']);
        $res['car'] = $car;
        return $res;
    }

    //已完成
    public function well_done($id)
    {
        $info = $this->details($id);

        if($info['travel_status'] !=1 ){
            $this->error = '订单状态错误，无法操作！';
            return false;
        }
        //更改车辆状态
        $res = $this->where(array('id'=>$id))->update(array('travel_status'=>2));
        //更改在用车辆状态
        $model = new CarOrderPlan();
        $model->where(array('order_id'=>$id))->update(array('status'=>2));
        return $res;
    }
    /*
     * 获取列表
     * */
    public function get_list($param)
    {
        if(isset($param['take_user_id'])){
            if($param['take_user_id']){
                $where[] = ['take_user_id','=',$param['take_user_id']];
            }
        }
        if(isset($param['user_id'])){
            if($param['user_id']){
                $where[] = ['user_id','=',$param['user_id']];
            }
        }
        if(isset($param['ordernum'])){
            if($param['ordernum']){
                $where[] = ['ordernum','=',$param['ordernum']];
            }

        }
        //用户订单状态
        if($param['status']){
            $where[] = ['status','=',$param['status']];
        }
        //车主接单状态
        if($param['status']){
            $where[] = ['status','=',$param['status']];
        }
        //出行状态
        if($param['travel_status']){
            $where[] = ['travel_status','=',$param['travel_status']];
        }

        $res = $this->with(['user','attestation'])->where($where)->paginate($param,false);
        foreach ($res as &$v){
            $v['star_time'] = date('Y-m-d H:i',$v['star_time']);
            $v['end_time'] = date('Y-m-d H:i',$v['end_time']);
            $star_address = json_decode($v['star_address'],1);
            $end_address = json_decode($v['end_address'],1);
            $v['lineInformation'] = json_decode($v['lineInformation'],1);
            //$v['address'] = $address;
            $v['star_address'] = $star_address;
            $v['end_address'] = $end_address;
            $v['driver_price'] = json_decode($v['driver_price'],1);

        }
        return $res;

    }

    //获取用户行程
    public function get_user_list($data)
    {
        $where2 = array();
        $where[] = ['is_delete','=',0];
        $time = time();

        //用户未支付
        if($data['status_type']==1){
            $where[] = ['status','=',0];
        }
        //用户已支付
        if($data['status_type']==2){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','<',1];
        }
        //未出行
        if($data['status_type']==3){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',1];
            //$where[] = ['travel_status','=',0];
            $where[] = ['star_time','>',$time];
        }
        //行驶中
        if($data['status_type']==4){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',1];
            //$where[] = ['travel_status','=',1];
            $where[] = ['star_time','<',$time];
            $where[] = ['end_time','>',$time];
        }
        //已完成
        if($data['status_type']==5){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',1];
            //$where[] = ['travel_status','=',2];
            $where[] = ['end_time','<',$time];
        }
        //退单中
        if($data['status_type']==6){
            $where[] = ['status','=',3];
        }
        //已退单
        if($data['status_type']==7){
            $where[] = ['status','=',2];
        }
        //退单驳回
        if($data['status_type']==8){
            $where[] = ['status','=',4];
        }
//        //未出行
//        if($data['status_type']==3){
//            $where[] = ['status','=',1];
//            $where[] = ['owner_status','=',1];
//            $where[] = ['travel_status','=',0];
//        }
//        //行驶中
//        if($data['status_type']==4){
//            $where[] = ['status','=',1];
//            $where[] = ['owner_status','=',1];
//            $where[] = ['travel_status','=',1];
//        }
//        //已完成
//        if($data['status_type']==5){
//            $where[] = ['status','=',1];
//            $where[] = ['owner_status','=',1];
//            $where[] = ['travel_status','=',2];
//        }
        //$where2 = $where;
        if($data['ordernum']){
            $where[] = ['star_address|end_address','like',"%{$data['ordernum']}%"];
            //$where2[] = ['end_address','like',"%{$data['ordernum']}%"];
        }
        $where[] = ['user_id','=',$data['user_id']];
        $res = $this->with(['user','attestation'])->where($where)->order("create_time desc")->paginate($data,false);
        foreach ($res as &$v){
            if($v['star_time']>$time){
                $v['travel_status'] = 0;
            }
            if($v['star_time']<$time && $v['end_time']>$time){
                $v['travel_status'] = 1;
            }
            if($v['end_time']<$time){
                $v['travel_status'] = 2;
            }
            $v['star_time'] = date('Y-m-d H:i',$v['star_time']);
            $v['end_time'] = date('Y-m-d H:i',$v['end_time']);
            $star_address = json_decode($v['star_address'],1);
            $end_address = json_decode($v['end_address'],1);
            $v['lineInformation'] = json_decode($v['lineInformation'],1);
            //$v['address'] = $address;
            $v['star_address'] = $star_address;
            $v['end_address'] = $end_address;
            $v['driver_price'] = json_decode($v['driver_price'],1);

        }
        return $res;
    }
    //获取车主行程
    public function get_owner_list($data)
    {
        $where[] = ['is_delete','=',0];
        $where2 = array();
        $time = time();
        if($data['ordernum']){
            $where[] = ['star_address|end_address','like',"%{$data['ordernum']}%"];
            //$where2[] = ['end_address','like',"%{$data['ordernum']}%"];
        }
        //未支付
        if($data['status_type']==1){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',0];
        }
        //已支付
        if($data['status_type']==2){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',1];
        }
        //未出行
        if($data['status_type']==3){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',1];
            //$where[] = ['travel_status','=',0];
            $where[] = ['star_time','>',$time];
        }
        //行驶中
        if($data['status_type']==4){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',1];
            //$where[] = ['travel_status','=',1];
            $where[] = ['star_time','<',$time];
            $where[] = ['end_time','>',$time];
        }
        //已完成
        if($data['status_type']==5){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',1];
            //$where[] = ['travel_status','=',2];
            $where[] = ['end_time','<',$time];
        }
        //退单中
        if($data['status_type']==6){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',3];
        }
        //已退单
        if($data['status_type']==7){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',2];
        }
        //退单驳回
        if($data['status_type']==8){
            $where[] = ['status','=',1];
            $where[] = ['owner_status','=',4];
        }
        $where[] = ['take_user_id','=',$data['take_user_id']];
        $res = $this->with(['user','attestation'])->where($where)->order("create_time desc")->paginate($data,false);
        foreach ($res as &$v){
            if($v['star_time']>$time){
                $v['travel_status'] = 0;
            }
            if($v['star_time']<$time && $v['end_time']>$time){
                $v['travel_status'] = 1;
            }
            if($v['end_time']<$time){
                $v['travel_status'] = 2;
            }
            $v['star_time'] = date('Y-m-d H:i',$v['star_time']);
            $v['end_time'] = date('Y-m-d H:i',$v['end_time']);
            $star_address = json_decode($v['star_address'],1);
            $end_address = json_decode($v['end_address'],1);
            $v['lineInformation'] = json_decode($v['lineInformation'],1);
            //$v['address'] = $address;
            $v['star_address'] = $star_address;
            $v['end_address'] = $end_address;
            $v['driver_price'] = json_decode($v['driver_price'],1);

        }
        return $res;
    }

    /*
     * 后台获取列表
     * */
    public function get_list_admin($param)
    {

        $car_model = new CarOrderPlan();
        $where2 = array();
        $where[] = ['is_delete','=',0];
        if($param['status'] !=null){
            $where[] = ['status','=',$param['status']];
        }
        if($param['owner_status'] !=null){
            $where[] = ['owner_status','=',$param['owner_status']];
        }
        if($param['travel_status'] !=null){
            $time = time();
            if($param['travel_status']==0){
                $where[] = ['star_time','>',$time];
            }
            if($param['travel_status']==1){
                $where[] = ['star_time','<',$time];
                $where[] = ['end_time','>',$time];
            }
            if($param['travel_status']==2){
                $where[] = ['end_time','<',$time];
            }

        }
        if($param['order_no']){
            $where[] = ['star_address|end_address','like',"%{$param['order_no']}%"];
            //$where2[] = ['end_address','like',"%{$param['order_no']}%"];
            //$where[] = ['ordernum','=',$param['order_no']];
        }
        if($param['reg_date']){
            if($param['reg_date'][0] == $param['reg_date'][1]){
                $param['reg_date'][0] = strtotime($param['reg_date'][0].' 00:00:00');
                $param['reg_date'][1] = strtotime($param['reg_date'][1].' 23:59:59');
            }else{
                $param['reg_date'][0] = strtotime($param['reg_date'][0].' 00:00:00');
                $param['reg_date'][1] = strtotime($param['reg_date'][1].' 23:59:59');
            }
            $where[] = ['create_time','between',$param['reg_date']];
        }

        $user_model = new User();

        $res = $this->with(['user','takeruser'])->where($where)->order("create_time desc")->paginate($param,false);

        foreach($res as $v){

            $car = $car_model->alias('co')
                ->field('co.driver_name,co.driver_phone,c.car_number')
                ->join('jjjshop_car c','co.car_id=c.car_id','left')
                ->where(array('co.order_id'=>$v['id']))
                ->select()->toArray();

            $v['car'] = $car;
            $star_address = json_decode($v['star_address'],1);
            $end_address = json_decode($v['end_address'],1);

            $address = json_decode($v['lineInformation'],1);
            $v['address'] = $address;
            $v['star_address'] = $star_address['b_name'];
            $v['end_address'] = $end_address['d_name'];
            if($v['status']==0){
                $v['status_name'] = '用户未支付';
            }elseif ($v['status']==1){
                $v['status_name'] = '用户已支付';
            }elseif ($v['status']==3){
                $v['status_name'] = '退单申请中';
            }elseif ($v['status']==4){
                $v['status_name'] = '退单已驳回';
            }else{
                $v['status_name'] = '用户已取消';
            }
            if($v['owner_status']==0){
                $v['owner_status_name'] = '车主已接单';
            }elseif ($v['owner_status']==1){
                $v['owner_status_name'] = '车主已支付押金';
            }elseif ($v['owner_status']==2){
                $v['owner_status_name'] = '已退单';
            }elseif ($v['owner_status']==3){
                $v['owner_status_name'] = '退单申请中';
            }elseif ($v['owner_status']==4){
                $v['owner_status_name'] = '退单已驳回';
            }else{
                $v['owner_status_name'] = '未有车主接单';
            }
            if($v['star_time']>time()){
                $v['active'] = 0;
                $v['travel_status_name'] = '未出行';
            }
            if($v['star_time']<time() && $v['end_time']>time()){
                $v['active'] = 1;
                $v['travel_status_name'] = '进行中';
            }
            if($v['end_time']<time()){
                $v['active'] = 2;
                $v['travel_status_name'] = '已结束行程';
            }
            $v['star_time'] = date('Y-m-d H:i',$v['star_time']);
            $v['end_time'] = date('Y-m-d H:i',$v['end_time']);

        }

        return $res;
    }

    //获取接单列表
    public function get_list_days($param)
    {
        $where[] = ['status','=',1];
        $where[] = ['owner_status','=',-1];
        $where[] = ['is_delete','=',0];
        //今日
        if($param['day_type'] ==1){
            $times = $this->date_time(1);
            $where[] = ['create_time','between',$times];
        }
        //三日
        if($param['day_type'] ==2){
            $times = $this->date_time(2);
            $where[] = ['create_time','between',$times];

        }
        //一个月内
        if($param['day_type'] ==3){
            $times = $this->date_time(6);
            $where[] = ['create_time','between',$times];
        }
        if($param['order_type']){
            $where[] = ['order_type','=',$param['order_type']];
        }


        $list = $this->with(['user','attestation'])->where($where)->order("create_time desc")->paginate($param,false);
        foreach ($list as &$v){
            $v['star_time'] = date('Y-m-d H:i',$v['star_time']);
            $v['end_time'] = date('Y-m-d H:i',$v['end_time']);
            $star_address = json_decode($v['star_address'],1);
            $end_address = json_decode($v['end_address'],1);
            $v['lineInformation'] = json_decode($v['lineInformation'],1);
            //$v['address'] = $address;
            $v['star_address'] = $star_address;
            $v['end_address'] = $end_address;
            $v['driver_price'] = json_decode($v['driver_price'],1);

        }
        return $list;
    }

    //用户申请退单
    public function user_cancel_apply($id,$reason){
        $data = array(
            'status'=>3,
            'cancel_time'=>time(),
            'reason'=>$reason
        );
        $res = $this->where(array("id"=>$id))->update($data);
        return $res;
    }
    //车主申请退单
    public function owner_cancel_apply($id,$reason){
        $data = array(
            'owner_status'=>3,
            'cancel_time'=>time(),
            'reason'=>$reason
        );
        $res = $this->where(array("id"=>$id))->update($data);
        return $res;
    }

    //后台处理退单申请
    public function cancel_order($data)
    {
        $info = $data['info'];
        $id = $data['id'];
        $status = $data['status'];
        if($status==4){//驳回
            if($info['status'] == 3){
                $res = $this->where(array('id'=>$id))->update(array('status'=>$status));
            }
            if($info['owner_status'] == 3){
                $res = $this->where(array('id'=>$id))->update(array('owner_status'=>$status));
            }

        }else{ //同意
            if($info['status'] == 3){
                $user_model = new User();
                $res = $this->user_cancel($id,$user_model->find($info['user_id']));
            }
            if($info['owner_status'] == 3){
                $res = $this->owner_return($id,$user_model->find($info['user_id']));
            }
        }

        return $res;

    }

    //用户取消订单
    public function user_cancel($id,$user)
    {
        //判断车主是否接单
        $info = $this->details($id);
        $money = $info['front_money'];//需退还金额
        //dump($money);die;
        //如果金额大于0
        if($money>0){
            $user_model = new User;
            $balance_model = new BalanceLog();
            //车主已接单，如果已接单，则应退还车主的押金
            if($info['owner_status'] ==1){
                //已出行或已完成
                if($info['travel_status']==1 || $info['travel_status']==2){
                    $this->error = '该订单无法取消！';
                    return false;
                }else{
                    //退还车主

                    $owner = $user_model->detail($info['take_user_id']);
                    $owner_money = $money+$owner['balance'];
                    $user_model->where(array('user_id'=>$info['take_user_id']))->update(array('balance'=>$owner_money));
                    $balance_model->add(40,array('user_id'=>$info['take_user_id'],'money'=>$owner_money),$owner_money);
                }
            }
            //退还用户
            $user_money = $user['balance']+$money;
            $user_model->where(array('user_id'=>$user['user_id']))->update(array('balance'=>$user_money));

            $balance_model->add(40,array('user_id'=>$info['user_id'],'money'=>$money),$money);
        }

        //改变状态
        $res = $this->where(array('id'=>$id))->update(array('status'=>2));
        if($res){
            //更改车辆
            $car_model = new CarOrderPlan();
            $car_model->where(array('order_id'=>$id))->update(array('status'=>2));
        }
        return $res;

    }

    //车主退单
    public function owner_return($id,$owner)
    {
        $info = $this->details($id);
        $money = $info['front_money'];//需退还金额
        if($info['travel_status']==1 || $info['travel_status']==2){
            $this->error = '该订单无法取消！';
            return false;
        }
        if($money>0){
            $user_model = new User;
            $balance_model = new BalanceLog();
            //退还用户
            $user = $user_model->detail($info['user_id']);
            $user_money = $user['balance']+$money;
            $user_model->where(array('user_id'=>$info['user_id']))->update(array('balance'=>$user_money));
            $balance_model->add(40,array('user_id'=>$info['user_id'],'money'=>$user_money),$user_money);
            if($info['owner_status']==1){
                //退还车主
                $owner_money = $money+$owner['balance'];
                $user_model->where(array('user_id'=>$info['take_user_id']))->update(array('balance'=>$owner_money));
                $balance_model->add(40,array('user_id'=>$info['take_user_id'],'money'=>$money),$money);
            }

        }
        //改变状态
        $res = $this->where(array('id'=>$id))->update(array('owner_status'=>2));
        if($res){
            //更改车辆
            $car_model = new CarOrderPlan();
            $car_model->where(array('order_id'=>$id))->update(array('status'=>2));
        }
        return $res;
    }

    //开始行程
    public function start_order($order_id)
    {
        $info = $this->find($order_id);
        if($info['status'] == 2){
            $this->error = '用户已取消订单';
            return false;
        }
        if($info['owner_status'] !=1){
            $this->error = '订单状态错误，无法开始行程！';
            return false;
        }
        $res = $this->where(array('id'=>$order_id))->update(array('travel_status'=>1));
        if(!$res){
            $this->error = '操作失败';
            return false;
        }
        return $res;
    }

    /*
     * 检查订单
     * */
    public function check_order($id)
    {
        $res = $this->find($id);
        if($res['status'] ==0){
             $this->error = '此订单用户未支付';
            return false;
        }elseif ($res['status'] ==2){
             $this->error = '此订单用户已取消';
            return false;
        }

        if($res['owner_status'] !=-1){
            $this->error = '此订单已有车主接单';
            return false;
        }

        return true;
    }

    /*
     * 获取总量
     *  type 1总数量，2当日，3当月,4上月,5昨日
     */
    public function get_all($daytype)
    {
        $where = array();

        if($daytype==2){

            $times = $this->date_time(1);
            $where[] = ['create_time','between',$times];
        }
        if($daytype==3){
            $times = $this->date_time(3);
            $where[] = ['create_time','between',$times];
        }
        if($daytype==4){
            $times = $this->date_time(4);
            $where[] = ['create_time','between',$times];
        }
        if($daytype==5){
            $times = $this->date_time(5);
            $where[] = ['create_time','between',$times];
        }

        $where[] = ['is_delete','=',0];
        $count = $this->where($where)->count();//订单数量

        return $count;
    }

    //获取已完成订单数
    public function get_all_done($type)
    {
        $times = $this->date_time($type);
        $where[] = ['is_delete','=',0];
        $where[] = ['create_time','between',$times];
        $where[] = ['travel_status','=',2];
        $count = $this->where($where)->count();//订单数量

        return $count;
    }

    //获取已支付订单数
    public function get_all_pay($type)
    {
        $times = $this->date_time($type);
        $where[] = ['is_delete','=',0];
        $where[] = ['create_time','between',$times];
        $where[] = ['status','=',1];
        $count = $this->where($where)->count();//订单数量

        return $count;
    }

    /*
     * 获取订单数量
     * */
    public function get_count($where)
    {
        $where[] = ['is_delete','=',0];
        $count = $this->where($where)->count();//订单数量

        return $count;
    }

    //获取本月销售额
    public function get_month_sale($type)
    {
        $times = $this->date_time($type);
        $where[] = ['status','=',1];
        $where[] = ['create_time','between',$times];
        $sum = $this->where($where)->sum('price');

        return $sum;
    }

    public function get_owner_order($type,$status)
    {
        $times = $this->date_time($type);
        $where[] = ['create_time','between',$times];
        $where[] = ['owner_status','=',$status];
        $where[] = ['is_delete','=',0];
        $sum = $this->where($where)->count();
        
        return $sum;
    }

    public function get_order_day_count($data)
    {
        $where = [];

        if($data['date']){
            $times = $this->get_time($data);
            $where[] = ['create_time','between',$times['date']];
        }
        //未支付
        $where1[] = ['status','=',0];
        $count_1 = $this->field(" COUNT(*) as tnum_1,sum(price) as amount_1, FROM_UNIXTIME(create_time,'%Y-%m-%d') as gap")
            ->group('gap')
            ->where($where1)->where($where)
            ->select()->toArray();

        //已支付
        $where2[] = ['status','=',1];
        $count_2 = $this->field(" COUNT(*) as tnum_2,sum(price) as amount_2, FROM_UNIXTIME(create_time,'%Y-%m-%d') as gap")
            ->group('gap')->where($where2)->where($where)->select()->toArray();

        //用户已取消
        $where3[] = ['status','=',2];
        $count_3 = $this->field(" COUNT(*) as tnum_3,sum(price) as amount_3, FROM_UNIXTIME(create_time,'%Y-%m-%d') as gap")
            ->group('gap')->where($where3)->where($where)->select()->toArray();

        //未接单
        $where4[] = ['owner_status','=',0];
        $count_4 = $this->field(" COUNT(*) as tnum_4,sum(price) as amount_4, FROM_UNIXTIME(create_time,'%Y-%m-%d') as gap")
            ->group('gap')->where($where2)->where($where)->where($where4)->select()->toArray();

        //已接单
        $where5[] = ['owner_status','=',1];
        $count_5 = $this->field(" COUNT(*) as tnum_5,sum(price) as amount_5, FROM_UNIXTIME(create_time,'%Y-%m-%d') as gap")
            ->group('gap')->where($where2)->where($where)->where($where5)->select()->toArray();

        //车主已取消
        $where6[] = ['owner_status','=',2];
        $count_6 = $this->field(" COUNT(*) as tnum_6,sum(price) as amount_6, FROM_UNIXTIME(create_time,'%Y-%m-%d') as gap")
            ->group('gap')->where($where2)->where($where)->where($where6)->select()->toArray();

        //已完成
        $where7[] = ['travel_status','=',2];
        $count_7 = $this->field(" COUNT(*) as tnum_7,sum(price) as amount_7, FROM_UNIXTIME(create_time,'%Y-%m-%d') as gap")
            ->group('gap')->where($where2)->where($where)->where($where5)->where($where7)->select()->toArray();

        $info = array_merge ($count_1,$count_2,$count_3,$count_4,$count_5,$count_6,$count_7);
        $arr = array();
        foreach($info as $v){
            $arr[] = $v['gap'];
        }
        $date = array_unique($arr);
        asort($date);
        foreach($date as $k=>$v){
            $ar[$k]['days'] = $v;
            $ar[$k]['tnum_7'] = 0;
            $ar[$k]['tnum_6'] = 0;
            $ar[$k]['tnum_5'] = 0;
            $ar[$k]['tnum_4'] = 0;
            $ar[$k]['tnum_3'] = 0;
            $ar[$k]['tnum_2'] = 0;
            $ar[$k]['tnum_1'] = 0;
            foreach($info as $vv){
                if($v==$vv['gap']){

                    if(isset($vv['tnum_7'])){
                        $ar[$k]['tnum_7'] = $vv['tnum_7'];
                        //$ar[$k]['amount_7'] = $vv['amount_7'];
                    }
                    if(isset($vv['tnum_6'])){
                        $ar[$k]['tnum_6'] = $vv['tnum_6'];
                        //$ar[$k]['amount_6'] = $vv['amount_6'];
                    }
                    if(isset($vv['tnum_5'])){
                        $ar[$k]['tnum_5'] = $vv['tnum_5'];
                        //$ar[$k]['amount_5'] = $vv['amount_5'];
                    }
                    if(isset($vv['tnum_4'])){
                        $ar[$k]['tnum_4'] = $vv['tnum_4'];
                        //$ar[$k]['amount_4'] = $vv['amount_4'];
                    }
                    if(isset($vv['tnum_3'])){
                        $ar[$k]['tnum_3'] = $vv['tnum_3'];
                        //$ar[$k]['amount_3'] = $vv['amount_3'];
                    }
                    if(isset($vv['tnum_2'])){
                        $ar[$k]['tnum_2'] = $vv['tnum_2'];
                        //$ar[$k]['amount_2'] = $vv['amount_2'];
                    }
                    if(isset($vv['tnum_1'])){
                        $ar[$k]['tnum_1'] = $vv['tnum_1'];
                        //$ar[$k]['amount_1'] = $vv['amount_1'];
                    }

                }
            }
        }
        $last_names = array_column($ar,'days');
        array_multisort($last_names,SORT_DESC,$ar);
        return $ar;
    }

    //月订单统计
    public function get_order_months($data)
    {

        $where = [];


        if($data['date']){

            $now = strtotime($data['date'][0]);

            $stime = strtotime(date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m', $now), '1', date('Y', $now))));
            $etime = strtotime(date('Y-m-d 23:39:59', mktime(0, 0, 0, date('m', $now), date('t', $now), date('Y', $now))));
            $data['date'][0] = $stime;
            $data['date'][1] = $etime;
            $where[] = ['create_time','between',[$stime,$etime]];
        }
        //未支付
        $where1[] = ['status','=',0];
        $count_1 = $this->field(" COUNT(*) as tnum_1,sum(price) as amount_1, FROM_UNIXTIME(create_time,'%Y-%m') as gap")
            ->group('gap')
            ->where($where1)->where($where)
            ->select()->toArray();

        //已支付
        $where2[] = ['status','=',1];
        $count_2 = $this->field(" COUNT(*) as tnum_2,sum(price) as amount_2, FROM_UNIXTIME(create_time,'%Y-%m') as gap")
            ->group('gap')->where($where2)->where($where)->select()->toArray();

        //用户已取消
        $where3[] = ['status','=',2];
        $count_3 = $this->field(" COUNT(*) as tnum_3,sum(price) as amount_3, FROM_UNIXTIME(create_time,'%Y-%m') as gap")
            ->group('gap')->where($where3)->where($where)->select()->toArray();

        //未接单
        $where4[] = ['owner_status','=',0];
        $count_4 = $this->field(" COUNT(*) as tnum_4,sum(price) as amount_4, FROM_UNIXTIME(create_time,'%Y-%m') as gap")
            ->group('gap')->where($where2)->where($where)->where($where4)->select()->toArray();

        //已接单
        $where5[] = ['owner_status','=',1];
        $count_5 = $this->field(" COUNT(*) as tnum_5,sum(price) as amount_5, FROM_UNIXTIME(create_time,'%Y-%m') as gap")
            ->group('gap')->where($where2)->where($where)->where($where5)->select()->toArray();

        //车主已取消
        $where6[] = ['owner_status','=',2];
        $count_6 = $this->field(" COUNT(*) as tnum_6,sum(price) as amount_6, FROM_UNIXTIME(create_time,'%Y-%m') as gap")
            ->group('gap')->where($where2)->where($where)->where($where6)->select()->toArray();

        //已完成
        $where7[] = ['travel_status','=',2];
        $count_7 = $this->field(" COUNT(*) as tnum_7,sum(price) as amount_7, FROM_UNIXTIME(create_time,'%Y-%m') as gap")
            ->group('gap')->where($where2)->where($where)->where($where5)->where($where7)->select()->toArray();

        $info = array_merge ($count_1,$count_2,$count_3,$count_4,$count_5,$count_6,$count_7);

        $arr = array();
        foreach($info as $v){
            $arr[] = $v['gap'];
        }
        $date = array_unique($arr);
        asort($date);
        foreach($date as $k=>$v){
            $ar[$k]['days'] = $v;
            $ar[$k]['tnum_7'] = 0;
            $ar[$k]['tnum_6'] = 0;
            $ar[$k]['tnum_5'] = 0;
            $ar[$k]['tnum_4'] = 0;
            $ar[$k]['tnum_3'] = 0;
            $ar[$k]['tnum_2'] = 0;
            $ar[$k]['tnum_1'] = 0;
            foreach($info as $vv){
                if($v==$vv['gap']){
                    if(isset($vv['tnum_7'])){
                        $ar[$k]['tnum_7'] = $vv['tnum_7'];
                        //$ar[$k]['amount_7'] = $vv['amount_7'];
                    }
                    if(isset($vv['tnum_6'])){
                        $ar[$k]['tnum_6'] = $vv['tnum_6'];
                        //$ar[$k]['amount_6'] = $vv['amount_6'];
                    }
                    if(isset($vv['tnum_5'])){
                        $ar[$k]['tnum_5'] = $vv['tnum_5'];
                        //$ar[$k]['amount_5'] = $vv['amount_5'];
                    }
                    if(isset($vv['tnum_4'])){
                        $ar[$k]['tnum_4'] = $vv['tnum_4'];
                        //$ar[$k]['amount_4'] = $vv['amount_4'];
                    }
                    if(isset($vv['tnum_3'])){
                        $ar[$k]['tnum_3'] = $vv['tnum_3'];
                        //$ar[$k]['amount_3'] = $vv['amount_3'];
                    }
                    if(isset($vv['tnum_2'])){
                        $ar[$k]['tnum_2'] = $vv['tnum_2'];
                        //$ar[$k]['amount_2'] = $vv['amount_2'];
                    }
                    if(isset($vv['tnum_1'])){
                        $ar[$k]['tnum_1'] = $vv['tnum_1'];
                        //$ar[$k]['amount_1'] = $vv['amount_1'];
                    }

                }
            }
        }

        $last_names = array_column($ar,'days');
        array_multisort($last_names,SORT_DESC,$ar);

        $info = $ar;


        return $info;
    }
    //时间区间
    public function date_time($type,$times=null)
    {
        if($times == null){
            $times = time();
        }
        //当日
        if($type == 1){
            $stime=strtotime(date("Y-m-d",$times));
            $etime=$stime+60*60*24;
        }
        //三日
        if($type == 2){
            $now = $times;
            $time = strtotime('-2 day', $now);
            $stime = strtotime(date('Y-m-d 00:00:00', $time));
            $etime = strtotime(date('Y-m-d 23:59:59', $now));

        }

        //本月
        if($type == 3){
            $now = $times;
            $stime = strtotime(date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m', $now), '1', date('Y', $now))));
            $etime = strtotime(date('Y-m-d 23:39:59', mktime(0, 0, 0, date('m', $now), date('t', $now), date('Y', $now))));

        }
        //上月
        if($type==4){
            $timestamp=$times;
            $stime=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));

            $etime=strtotime(date('Y-m-d',strtotime("$stime +1 month -1 day")));

            $stime = strtotime($stime);
        }
        //昨日
        if($type==5){
            $times = date("Y-m-d",strtotime("-1 day"));
            $stime = strtotime($times." 00:00:00");
            $etime=strtotime($times.' 23:59:59');
        }
        //一个月内
        if($type==6){
            $now = $times;
            $time = strtotime('-30 day', $now);
            $stime = strtotime(date('Y-m-d 00:00:00', $time));
            $etime = strtotime(date('Y-m-d 23:59:59', $now));
        }

        return [$stime,$etime];

    }

    public function get_time($data)
    {
        if($data['date'][0] == $data['date'][1]){
            $time['date'][0] = strtotime($data['date'][0].' 00:00:00');
            $time['date'][1] = strtotime($data['date'][1].' 23:59:59');
        }else{
            $time['date'][0] = strtotime($data['date'][0].' 00:00:00');
            $time['date'][1] = strtotime($data['date'][1].' 23:59:59');
        }
        return $time;
    }



}